<?php

declare(strict_types=1);

namespace magein\laravel\seecms\middleware;

use Closure;
use Illuminate\Http\Request;
use magein\seecms\Factory;
use magein\seecms\library\Auth;
use magein\utils\Result;

/**
 * 验证权限
 */
class PermissionMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user()->isRoot()) {
            return $next($request);
        }

        /**
         * nginx pathinfo模式下$request->pathinfo()为空
         *
         * 所以取$request->baseUrl()
         */
        $pathinfo = $request->pathinfo() ?: $request->baseUrl();
        $pathinfo = trim($pathinfo, '/');
        if (!preg_match('/^admin/', $pathinfo)) {
            $pathinfo = 'admin/' . $pathinfo;
        }

        // 处理成点分割的形式
        $pathinfo_split = str_replace('/', '.', $pathinfo);

        // 不需要权限访问权限的路由
        $allow = [
            's/profile/*',
            's/home/*',
            's/attachment/*'
        ];
        // 配置文件中排除验证的地址
        $expects = config('cms.permission.expects', []);
        $expects = array_merge($expects, $allow);

        $flag = false;
        foreach ($expects as $expect) {
            $expect = 'admin/' . $expect;
            $expect = preg_replace(['/\//', '/\*/'], ['\.', '.*?'], $expect);
            if (preg_match("/^$expect/", $pathinfo_split)) {
                $flag = true;
                break;
            }
        }

        if ($flag) {
            return $next($request);
        }

        $user_rule = Auth::user()->rule();

        $url = trim($pathinfo, 'admin');
        $url = trim($url, '/');

        if (!in_array($url, $user_rule)) {
            // 验证用户权限
            if ($request->isAjax()) {
                return json(Result::error('No access permission', 3003, ['url' => $url])->toArray());
            } else {
                return redirect(Factory::route('/u/user/noPermission?url=' . $url));
            }
        }

        return $next($request);
    }
}
